package com.sanqing.main;

import javax.swing.*;

import com.sanqing.dao.Dao;
import com.sanqing.iframe.BookLoginIFrame;
import com.sanqing.model.Borrow;
import com.sanqing.model.RecommenderInfo;
import com.sanqing.model.Reserve;
import com.sanqing.model.common;

import javax.swing.border.BevelBorder;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

public class Library extends JFrame {
	private static final JDesktopPane DESKTOP_PANE = new JDesktopPane();// 桌面窗体
	private static final int ICON_WIDTH = 24; // 图标宽度
	private static final int ICON_HEIGHT = 24; // 图标高度

	public static void main(String[] args) {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());// 设置系统界面外观
			SwingUtilities.invokeLater(() -> {
				BookLoginIFrame loginFrame = new BookLoginIFrame();
				loginFrame.setVisible(true);
			});
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public static void addIFame(JInternalFrame iframe) {// 添加子窗体的方法
		DESKTOP_PANE.add(iframe);// 新增子窗体
	}

	public Library() {
		super(); // 调用父类构造方法
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); // 关闭按钮处理事件

		// 设置窗口位置和大小
		Toolkit tool = Toolkit.getDefaultToolkit();
		Dimension screenSize = tool.getScreenSize();
		setSize(900, 700);
		setLocation((screenSize.width - getWidth()) / 2, (screenSize.height - getHeight()) / 2);

		setTitle("图书馆管理系统-"+common.UserName);

		// 设置菜单栏
		JMenuBar menuBar = createMenu();
		setJMenuBar(menuBar);

		// 设置工具栏
		JToolBar toolBar = createToolBar();
		getContentPane().add(toolBar, BorderLayout.NORTH);

		// 设置背景图片
		try {
			// 加载背景图片
			ImageIcon backgroundIcon = new ImageIcon(getClass().getResource("/backImg.jpg"));

			// 创建一个显示背景图片的标签
			final JLabel backgroundLabel = new JLabel(backgroundIcon);

			// 确保标签随窗口大小变化而调整
			DESKTOP_PANE.addComponentListener(new ComponentAdapter() {
				public void componentResized(ComponentEvent e) {
					// 调整标签大小以适应窗口
					backgroundLabel.setSize(DESKTOP_PANE.getSize());

					// 调整图片大小以适应标签
					if (backgroundIcon != null && backgroundIcon.getImage() != null) {
						Image scaledImage = backgroundIcon.getImage().getScaledInstance(DESKTOP_PANE.getWidth(),
								DESKTOP_PANE.getHeight(), Image.SCALE_SMOOTH);
						backgroundLabel.setIcon(new ImageIcon(scaledImage));
					}
				}
			});

			// 将背景标签添加到桌面面板的最底层
			DESKTOP_PANE.add(backgroundLabel, new Integer(Integer.MIN_VALUE));

			// 初始化背景标签大小
			backgroundLabel.setSize(DESKTOP_PANE.getSize());

		} catch (Exception e) {
			// 如果加载图片失败，显示错误信息
			JLabel errorLabel = new JLabel("无法加载背景图片: " + e.getMessage());
			errorLabel.setHorizontalAlignment(JLabel.CENTER);
			errorLabel.setVerticalAlignment(JLabel.CENTER);
			DESKTOP_PANE.add(errorLabel, new Integer(Integer.MIN_VALUE));
			e.printStackTrace();
		}

		// 添加桌面面板到主窗口
		getContentPane().add(DESKTOP_PANE);
		this.setVisible(true);
		// 推荐检查
		List<RecommenderInfo> list = Dao.selectRecommenderInfo(common.UserName);
		for (int i = 0; i < list.size(); i++) {
			String message = "你推荐的: " + list.get(i).getISBN() + "已入馆,请及时查看";
			JOptionPane.showMessageDialog(null, message);
		}
		// 当前用户借阅检查
		DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
		String nowkDate = dateTimeFormatter.format(LocalDate.now().plusDays(6));

		List l = Dao.selectBorrow("select * from tb_borrow where readerISBN='" + BookLoginIFrame.getOperator().getISBN()
				+ "' and isback = 0 and backDate<='" + nowkDate + "'");
		int n = l.size();
		if (n > 0) {
			for (int i = 0; i < n; i++) {
				String message = "你的ISBN为: " + ((Borrow)l.get(i)).getBookISBN() + "的书籍快超时或已经超时未归还";
				JOptionPane.showMessageDialog(null, message, "提示", JOptionPane.PLAIN_MESSAGE);
			}

		}

		common.check(); // 检查预约信息

		l = Dao.selectReserve("select * from tb_reserve where reserveDate IS NOT NULL and readerISBN='"+BookLoginIFrame.getOperator().getISBN()+"'");
		n = l.size();
		//System.out.println(n);
		if (n > 0) {
			for (int i = 0; i < n; i++) {
				String message = "你预约的ISBN为: " + ((Reserve)l.get(i)).getbookISBN() + "的图书已可以借阅";
				JOptionPane.showMessageDialog(null, message, "提示", JOptionPane.PLAIN_MESSAGE);
			}

		}

	}

	// 调整图标大小的辅助方法
	private ImageIcon resizeIcon(ImageIcon originalIcon, int width, int height) {
		if (originalIcon == null)
			return null;
		Image image = originalIcon.getImage();
		Image resizedImage = image.getScaledInstance(width, height, Image.SCALE_SMOOTH);
		return new ImageIcon(resizedImage);
	}

	// 创建菜单栏的方法
	private JMenuBar createMenu() {
		JMenuBar menuBar = new JMenuBar();
		menuBar.setFont(new Font("宋体", Font.PLAIN, 14));

		// 基础数据维护菜单
		JMenu baseMenu = new JMenu("基础数据维护");
		baseMenu.setFont(new Font("宋体", Font.BOLD, 14));

		// 读者信息管理子菜单
		JMenu readerManagerItem = new JMenu("读者信息管理");
		readerManagerItem.add(MenuActions.READER_ADD);
		readerManagerItem.add(MenuActions.READER_MODIFY);

		// 图书类别管理子菜单
		JMenu bookTypeManageItem = new JMenu("图书类别管理");
		bookTypeManageItem.add(MenuActions.BOOKTYPE_ADD);
		bookTypeManageItem.add(MenuActions.BOOKTYPE_MODIFY);

		// 图书信息管理子菜单
		JMenu bookManageItem = new JMenu("图书信息管理");
//        bookManageItem.add(MenuActions.BOOK_ADD);
		bookManageItem.add(MenuActions.BOOK_MODIFY);
		bookManageItem.add(MenuActions.BOOK_INFO);

		// 退出系统菜单项
		JMenuItem exitMenuItem = new JMenuItem(MenuActions.EXIT);
		baseMenu.add(readerManagerItem);
		baseMenu.add(bookTypeManageItem); 
		baseMenu.add(bookManageItem);
		baseMenu.addSeparator();
		baseMenu.add(exitMenuItem);

		// 新书订购管理菜单R
		JMenu bookOrderMenu = new JMenu("新书订购管理");
		bookOrderMenu.setFont(new Font("宋体", Font.BOLD, 14));
		JMenuItem newBookOrderMenuItem = new JMenuItem(MenuActions.NEWBOOK_ORDER);
		JMenuItem newBookCheckMenuItem = new JMenuItem(MenuActions.NEWBOOK_CHECK_ACCEPT);
		JMenuItem RecordCheckMenuItem = new JMenuItem(MenuActions.RECORD_CHECK);
		bookOrderMenu.add(newBookOrderMenuItem);
		bookOrderMenu.add(newBookCheckMenuItem);
		bookOrderMenu.add(RecordCheckMenuItem);

		// 借阅管理菜单
		JMenu borrowManageMenu = new JMenu("借阅管理");
		borrowManageMenu.setFont(new Font("宋体", Font.BOLD, 14));
		JMenuItem borrowMenuItem = new JMenuItem(MenuActions.BORROW);
		JMenuItem giveBackMenuItem = new JMenuItem(MenuActions.GIVE_BACK);
		JMenuItem searchMenuItem = new JMenuItem(MenuActions.BOOK_SEARCH);
		JMenuItem reserveMenuItem = new JMenuItem(MenuActions.BOOK_RESERVE);
		JMenuItem revokereserveMenuItem = new JMenuItem(MenuActions.reserve_revoke);
		borrowManageMenu.add(borrowMenuItem);
		borrowManageMenu.add(reserveMenuItem);
		borrowManageMenu.add(giveBackMenuItem);
		borrowManageMenu.add(searchMenuItem);
		borrowManageMenu.add(revokereserveMenuItem);

		// 系统维护菜单
		JMenu sysManageMenu = new JMenu("系统维护");
		sysManageMenu.setFont(new Font("宋体", Font.BOLD, 14));
		// 更改口令菜单项（假设 MenuActions 有对应动作）
		// JMenuItem changePasswordMenuItem = new
		// JMenuItem(MenuActions.CHANGE_PASSWORD);
		JMenu userManageMenuItem = new JMenu("用户管理");
		userManageMenuItem.add(MenuActions.USER_ADD);
		userManageMenuItem.add(MenuActions.USER_MODIFY);
		// sysManageMenu.add(changePasswordMenuItem);
		sysManageMenu.add(userManageMenuItem);

		menuBar.add(baseMenu);
		menuBar.add(bookOrderMenu);
		menuBar.add(borrowManageMenu);
		menuBar.add(sysManageMenu);

		return menuBar;
	}

	// 创建工具栏的方法 - 添加了工具栏提示
	private JToolBar createToolBar() {
		JToolBar toolBar = new JToolBar();
		toolBar.setFloatable(false);
		toolBar.setBorder(new BevelBorder(BevelBorder.RAISED));

		// 添加工具栏按钮，使用调整后的图标并设置提示文本
//        addToolBarButton(toolBar, MenuActions.BOOK_ADD, "res/bookAddtb.jpg", "添加图书");
		addToolBarButton(toolBar, MenuActions.BOOK_INFO, "res/bookinfo.jpg", "图书查看");
		addToolBarButton(toolBar, MenuActions.BOOK_MODIFY, "res/bookModiAndDeltb.jpg", "修改/删除图书");
		addToolBarButton(toolBar, MenuActions.BOOKTYPE_ADD, "res/bookTypeAddtb.jpg", "添加图书类别");
		addToolBarButton(toolBar, MenuActions.BORROW, "res/bookBorrowtb.jpg", "图书借阅");
		addToolBarButton(toolBar, MenuActions.BOOK_RESERVE, "res/bookreserve.jpg", "图书预约");
		addToolBarButton(toolBar, MenuActions.NEWBOOK_ORDER, "res/bookOrdertb.jpg", "新书订购");
		addToolBarButton(toolBar, MenuActions.NEWBOOK_CHECK_ACCEPT, "res/newbookChecktb.jpg", "验收新书");
		addToolBarButton(toolBar, MenuActions.RECORD_CHECK, "res/recordcheck.jpg", "验收记录");
		addToolBarButton(toolBar, MenuActions.READER_ADD, "res/readerAddtb.jpg", "添加读者");
		addToolBarButton(toolBar, MenuActions.READER_MODIFY, "res/readerModiAndDeltb.jpg", "修改/删除读者");
		addToolBarButton(toolBar, MenuActions.EXIT, "res/exitb.jpg", "退出系统");

		return toolBar;
	}

	// 添加工具栏按钮的辅助方法 - 增加了提示文本参数
	private void addToolBarButton(JToolBar toolBar, Action action, String iconPath, String toolTipText) {
		JButton button = new JButton(action);
		button.setIcon(resizeIcon(new ImageIcon(iconPath), ICON_WIDTH, ICON_HEIGHT));
		button.setHideActionText(true);
		button.setToolTipText(toolTipText); // 设置提示文本
		toolBar.add(button);
	}
}